package com.alex.controller.Pubmed;

import com.alex.controller.System.entity.ChatEntity;
import com.alibaba.fastjson2.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Tag(name = "Pubmed_孔柳茜")
@Controller
@RequestMapping("/pubmed")
@SuppressWarnings("all")
public class PubmedController {

    @Operation(summary = "生成 pubmed 的检索词", description = "接口以stream流式返回,参考各大 AI 聊天界面效果")
    @PostMapping("/pubmed__to_search_deepseek")
    public void pubmed__to_search_deepseek(@org.springframework.web.bind.annotation.RequestBody JSONObject jsonObject, HttpServletResponse httpServletResponse) throws IOException {
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        List<ChatEntity> msgEntities = new ArrayList<>();
        String content = jsonObject.getString("content");
        ChatEntity userEntity = new ChatEntity();
        userEntity.setRole("user");
        userEntity.setContent("在PubMed检索:\n\n" + content + "。" +
                "\n如何列检索式?请直接给我一条最完整,最标准的高级检索式,只返回检索式.不要多余解释");
        msgEntities.add(userEntity);
        httpServletResponse.setContentType("text/event-stream");
        httpServletResponse.setCharacterEncoding("UTF-8");
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(20, TimeUnit.SECONDS) // 设置连接超时时间为15秒
                .readTimeout(100, TimeUnit.SECONDS)    // 设置读取超时时间为30秒
                .build();
        Request request = sendMsgAliBaBa(msgEntities);
        Response response = null;
        try {
            //解析返回回来的答案
            response = client.newCall(request).execute();
        } catch (IOException e) {
            log.error("response请求错误");
            e.printStackTrace(System.err);
        }
        if (null != response) {
            ResponseBody responseBody = response.body();
            if (null != responseBody) {
                InputStream inputStream = responseBody.byteStream();
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                    String line = "";
                    StringBuilder stringBuilder = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        outputStream.write(line.getBytes(StandardCharsets.UTF_8));
                        outputStream.flush();
                    }
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            } else {
                outputStream.write(("\n. . . . . . .系统连接超时,请重新提问").getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
            }
        } else {
            outputStream.write(("\n. . . . . . .系统连接超时,请重新提问").getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
        }
    }


    public static Request sendMsgAliBaBa(List<ChatEntity> msgEntities) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("messages", JSONObject.toJSONString(msgEntities));
        map.put("model", "\"deepseek-r1\"");
        map.put("frequency_penalty", 0);
        map.put("max_tokens", 2000);
        map.put("presence_penalty", 0);
        map.put("stop", null);
        map.put("stream", true);
        map.put("temperature", 1);
        map.put("top_p", 0.9);
        String string = mapToString(map);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, string);
        Request request = new Request.Builder().url("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer sk-c65ee8baf0c440238e51f74495107da3")
                .build();
        return request;
    }

    public static String mapToString(Map<String, Object> map) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (stringBuilder.length() > 1) { // 避免第一个元素前出现逗号
                stringBuilder.append(",");
            }
            String key = entry.getKey();
            Object value = entry.getValue();
            stringBuilder.append("\"").append(key).append("\":").append(value);
        }
        stringBuilder.append("}");
        return stringBuilder.toString();
    }
}
